package controller.v2;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.paypal.api.payments.Links;
import com.paypal.api.payments.Payment;
import com.paypal.base.rest.PayPalRESTException;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import java.net.*;
import java.io.*;
import util.PaypalPayment;

@Controller
@RequestMapping(value = "/v2/paypal")
public class PaymentController {

	/**
	 * Sofort 支付接口
	 * 
	 * @param String
	 *            orderID；
	 * @return String paypalPayUrl;
	 * @throws Exception
	 */
	@RequestMapping(value = "/payment")
	public String sofortPayment(String orderID) {// throws Exception
		System.out.println(123);
		orderID = ((int)(Math.random()*1000))+"";
		String total = "0.01"; 
		Payment payment;
		try {
			payment = PaypalPayment.createPayment(total);
			for (Links links : payment.getLinks()) {
				if (links.getRel().equals("approval_url")) {
					return "redirect:"+links.getHref();// 客户付款登陆地址
				}
			}
		} catch (PayPalRESTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "system/pay/paypal/failedUrl";
	}

	@RequestMapping(value = "/cancelUrl")
	public String cancelPay() {
		return "system/pay/paypal/cancelUrl";
	}

	/**
	 * 客户登陆付款后paypal返回路径参数示例
	 * http://域名/paypal/returnUrl?paymentId=PAY-339981922W118522HLJLQF3A&token=EC-9K664484GE997692K&PayerID=LEBMCXS5RQ7AU
	 */
	@RequestMapping(value = "/returnUrl")
	@ResponseBody
	public String successPay(@RequestParam("paymentId") String paymentId, @RequestParam("PayerID") String payerId,HttpServletRequest request) {
		System.out.println("*********"+request.getParameter("a"));
		try {
			Payment payment = PaypalPayment.executePayment(paymentId, payerId);
			if (payment.getState().equals("approved")) {
				return "success";
			}
			return "success";
		} catch (PayPalRESTException e) {
			System.out.println(e.getMessage());
		}
		return "system/pay/paypal/failed";
	}

/*	public static void main(String[] args) throws PayPalRESTException {
		String total = "0.01";
		Payment payment = PaypalPayment.createPayment(total);
		for (Links links : payment.getLinks()) {
			if (links.getRel().equals("approval_url")) {
			}
		}
	}*/
	
	@RequestMapping(value = "/validate")
	public void validate(HttpServletRequest request) throws Exception {
		
		//从 PayPal 出读取 POST 信息同时添加变量„cmd‟  
	    Enumeration en = request.getParameterNames();  
	    String str = "cmd=_notify-validate";  
	    while (en.hasMoreElements()) {  
	        String paramName = (String) en.nextElement();  
	        String paramValue = request.getParameter(paramName);  
	        str = str + "&" + paramName + "="  
	                + URLEncoder.encode(paramValue, "utf-8");  
	        //此处的编码一定要和自己的网站编码一致，不然会出现乱码，paypal回复的通知为‘INVALID’  
	    }  
	    System.out.println("paypal#######:" + str);  
	    //建议在此将接受到的信息 str 记录到日志文件中以确认是否收到 IPN 信息  
	    //将信息 POST 回给 PayPal 进行验证  
	    //设置 HTTP 的头信息  
	    //在 Sandbox 情况下，设置：  
	    URL u = new URL("https://www.sandbox.paypal.com/cgi-bin/webscr");  
	    //正式环境  
	    //      URL u = new URL("https://www.paypal.com/cgi-bin/webscr");  
	    URLConnection uc = u.openConnection();  
	    uc.setDoOutput(true);  
	    uc.setRequestProperty("Content-Type",  
	            "application/x-www-form-urlencoded");  
	    PrintWriter pw = new PrintWriter(uc.getOutputStream());  
	    pw.println(str);  
	    pw.close();  
	    //接受 PayPal 对 IPN 回发的回复信息  
	    BufferedReader in = new BufferedReader(new InputStreamReader(  
	            uc.getInputStream()));  
	    String res = in.readLine();  
	    in.close();  
	  
	    //将 POST 信息分配给本地变量，可以根据您的需要添加  
	    //该付款明细所有变量可参考：  
	    //https://www.paypal.com/IntegrationCenter/ic_ipn-pdt-variable-reference.html  
	    String itemName = request.getParameter("item_name");//商品名  
	    String newString = new String(itemName.getBytes("gbk"),"utf-8");
	    System.out.println(URLDecoder.decode(request.getParameter("item_name"), "utf-8"));
	    String itemNumber = request.getParameter("item_number");//购买数量  
	    String paymentStatus = request.getParameter("payment_status");//交易状态  
	    String paymentDate = request.getParameter("payment_date");//交易时间  
	    String paymentAmount = request.getParameter("mc_gross");//交易钱数  
	    String paymentCurrency = request.getParameter("mc_currency");//货币种类  
	    String txnId = request.getParameter("txn_id");//交易id  
	    String receiverEmail = request.getParameter("receiver_email");//收款人email  
	    String payerEmail = request.getParameter("payer_email");//付款人email  
	  
	    if (res == null || res == "")  
	        res = "0";  
	    //…  
	    //获取 PayPal 对回发信息的回复信息，判断刚才的通知是否为 PayPal 发出的  
	    if (res.equals("VERIFIED")) {  
	        //检查付款状态  
	        //检查 txn_id 是否已经处理过  
	        //检查 receiver_email 是否是您的 PayPal 账户中的 EMAIL 地址  
	        //检查付款金额和货币单位是否正确  
	        //处理其他数据，包括写数据库  
	          System.out.println("################");
	          System.out.println(res);
	    } else if (res.equals("INVALID")) {  
	        //非法信息，可以将此记录到您的日志文件中以备调查  
	    	System.out.println("################");
	          System.out.println(res);
	    } else {  
	        //处理其他错误  
	    	System.out.println("################");
	          System.out.println(res);
	    }  
	}
	
	
	
	
}